﻿
module Sustainalytics.Account {

    import Common = Sustainalytics.Common;


    export class AccountService {
        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private $location: ng.ILocationService;
        private staticObjects: Common.IStaticObjects;

        //Ctor.
        constructor($q: ng.IQService, $http: ng.IHttpService, $location: ng.ILocationService, staticObjects: Common.IStaticObjects) {
            this.$q = $q;
            this.$http = $http;
            this.$location = $location;
            this.staticObjects = staticObjects;
        }

        // show error message for a given error code

        private getUrl(): string {
            return this.$location.protocol() + "://" + this.$location.host() + ":" + this.$location.port() + this.staticObjects.baseUrl
                + "/api/v1/account/";
        }


        public getAccountPermissions(accountId: string, type: PermissionTypeEnum) {
            var ctx = this;
            var def = this.$q.defer();

            var query =
                {
                    type: type,
                    isActive: true
                };

            var url = ctx.getUrl() + accountId + "/accountPermission" + "?" + $.param(query);

            var promise = this.$http.get(url);

            promise
                .success(function(data) {
                    def.resolve(data);
                })
                .error(function(err) {
                    def.reject();
                });

            return def.promise;
        }

        public getProductPermission(accountId: string, productName: string) {
            var ctx = this;
            var def = this.$q.defer();

            var query =
            {
                productName: productName
            };

            var url = ctx.getUrl() + accountId + "/productPermission" + "?" + $.param(query);

            var promise = this.$http.get(url);

            promise
                .success(function (data) {
                    def.resolve(data);
                })
                .error(function (err) {
                    def.reject();
                });

            return def.promise;
        }

    }


    // register service with Account Angular module
    angular.module('Sustainalytics.Account').service('AccountService',
        ['$q', '$http', '$location', 'staticObjects', AccountService]);
}